package java6681.bank;

import java6681.lesson13.BankAccount6681;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;


public class Bank6681Controller implements Runnable {

    @FXML
    private TextField tfBankID;

    @FXML
    private TextField tfBalance0;

    @FXML
    private Label lblErrMsg;

    @FXML
    private TextArea taMoney;

    @FXML
    private Label lblBalance;

    @FXML
    private TextArea taResult;

    private static BankAccount6681 account;

    @FXML
    void start6681(ActionEvent event) {

        String id = tfBankID.getText();
        String balance = tfBalance0.getText();
        account = new BankAccount6681(id, Integer.parseInt(balance));
        System.out.println(account.getBankID() +
                "账上开始余额" + account.getBalance() + "元");

        String[] num = taMoney.getText().split("\n");
        int length = num.length;
        Thread[] t = new Thread[length];

        Bank6681Controller b = new Bank6681Controller();
        for (int i = 0; i < length; i++) {
            t[i] = new Thread(b, "线程：" + i);
        }

        for (int i = 0; i < length; i++) {
            t[i].start();
            try {
                t[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(account.getBankID() +
                "账上最终余额" + account.getBalance() + "元");
    }

    @Override
    public void run() {
        String[] num = taMoney.getText().split("\n");

        String name = Thread.currentThread().getName();
        String action = "";
        int money = 0, b = 0;
            for (int x = 0; x < num.length; x++) {
                if (Integer.parseInt(num[x]) > 0) {
                    money += Integer.parseInt(num[x]);
                    action = "存入";
                } else if (Integer.parseInt(num[x]) < 0) {
                    money += Integer.parseInt(num[x]);
                    action = "取出";
                }
                System.out.println(name + action + Math.abs(Integer.parseInt(num[x])));
            }

        synchronized (BankAccount6681.class) {
            for (int i = 0; i < 1; i++) {
                b = account.getBalance() + money;

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                account.setBalance(b);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }}

